<template>
  <!-- 新增订单表格 -->
  <div class="common">
    <el-upload v-show="uploadeExls" :auto-upload="false" :on-change="uploadHandle" :show-file-list="false" accept=".xlsx,.xls"
               action>
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
    </el-upload>

    <el-table ref="multipleTableRef" :cell-class-name="cellClassName" :data="props.dataTable" :header-cell-style="{ 'color': '#fff', 'background': `${bg} !important`, 'border-right': '1px solid #fff' }" border class="table-new"
              max-height="600" min-height="330" stripe
              @selection-change="handleSelectionChange"
              @cell-click="updateFocusCell">
      <el-table-column v-if="updateFlag" :align="'center'" fixed="left" label="操作" width="100px">
        <template #default="scope">

          <div style="display: flex; justify-content: space-evenly; align-items: center; width: 100%;">
            <i v-show="props.dataTable.length != 1 && scope.row.deleteFlag && deleteFlag" class="iconfont icon-delete-s" style="color: #9419FF; font-size: 22px;"
               @click="deleteRow(scope)" ></i>
            <i v-show="props.dataTable.length != 1 && !deleteFlag" class="iconfont icon-delete-s" style="color: #9419FF; font-size: 22px;"
               @click="deleteRow(scope)" ></i>
            <i class="iconfont icon-fuzhi" style="color: #9419FF; font-size: 19px;"
               @click="copyRow(scope.row)"></i>
            <i class="iconfont icon-tianjia" style="color: #9419FF; font-size: 19px;" @click="createtable"></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="业务类型" width="120px">
        <template #header>
          <span style="color : red;margin-right: 5px;"> * </span>
          <span>业务类型</span>
        </template>

        <template #default="scope">
          <el-select v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)"
                     v-model="scope.row.businessType"
                     v-focus filterable :disabled="props.disabledFlagOuter">
            <el-option v-for="item in selectBusiness" :key="item.index" :label="item.label"
                       :value="item.label"/>
          </el-select>
          <div v-else>
            {{ scope.row.businessType }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" label="存货名称" width="120px">
        <template #default="scope">
          <el-select v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)"
                     v-model="scope.row.productId" v-focus filterable
                     popper-class="dropdownSelect"
                     @change="stocksChange(scope.row)" :disabled="props.disabledFlagOuter">
            <el-option v-for="item in apiStore.stocksData" :key="item.productId" :label="item.productName"
                       :value="item.productId"/>
          </el-select>
          <div v-else>
            {{ scope.row.productName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" fixed="left" show-overflow-tooltip label="制作内容" width="100px">

        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.productionContent"
                    v-focus cols="5"
                    resize='none'
                    type="textarea" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.productionContent }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="宽" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.width" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.width }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="高" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.height" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.height }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="件数" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.quantityPerPiece" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.quantityPerPiece }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="数量" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.totalQuantity" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else :class="scope.row.classErrorBorder ? 'classErrorBorder' : ''">
            {{ scope.row.totalQuantity }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="单位" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.unit" v-focus cols="5"
                    resize='none'
                    type="textarea" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.unit }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="销售单价" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.salePrice" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.salePrice }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="销售金额" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.amount" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.amount }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="成本单价" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.price" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.price }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="成本金额" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.salePriceAll" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.salePriceAll }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="预收款" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.prepayment" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.prepayment }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="材料费" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.materialFee" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.materialFee }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="外协商" width="160px">
        <template #default="scope">
          <el-select v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.outsourcingId" v-focus clearable
                     filterable
                     popper-class="dropdownSelect" @change="outsourcingChange(scope.row)" :disabled="props.disabledFlagOuter">
            <el-option v-for="item in apiStore.selectExternalDate" :key="item.outsourcingId"
                       :label="item.outsourcingName" :value="item.outsourcingId"/>
          </el-select>
          <div v-else>
            {{ scope.row.outsourcingName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="成本类型" width="100px">
        <template #default="scope">
          <el-select v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.costCategory"
                     v-focus
                     clearable filterable :disabled="props.disabledFlagOuter">
            <el-option v-for="item in selectCost" :key="item.index" :label="item.label" :value="item.label"/>
          </el-select>
          <div v-else>
            {{ scope.row.costCategory }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="预算成本" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.budgetCost" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="props.disabledFlagOuter"></el-input>
          <div v-else>
            {{ scope.row.budgetCost }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="实际成本" width="100px">
        <template #default="scope">
          <el-input v-if="focusCell == 'cellId' + ',' + String(scope.cellIndex) + ',' + String(scope.$index)" v-model="scope.row.actualCost" v-focus cols="5"
                    resize='none'
                    type="number" @keydown="(e)=>{handleNumberInput(e)}" :disabled="scope.row.voucherStatusItem == '已生成'"></el-input>
          <div v-else>
            {{ scope.row.actualCost }}
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="count">
      <!-- <label>
          总宽：
          <span>{{ sumWidth }}</span>
      </label>
      <label>
          总高：
          <span>{{ sumHeight }}</span>
      </label> -->
      <label>
        总件数：
        <span>{{ sumQuantityPerPiece }}</span>
      </label>
      <!-- <label>
          总数量：
          <span>{{ sumNumber }}</span>
      </label> -->
      <label>
        总销售单价：
        <span>{{ sumSalePrice }}</span>
      </label>
      <!-- <label>
          总销售金额：
          <span>{{sumAmount}}</span>
      </label> -->

    </div>
  </div>
</template>
<script setup>
import {defineEmits, defineProps, onMounted, ref} from 'vue'
import {ElTable} from 'element-plus'
import {inputSearchHandler} from '@/hook/inputChange'
import {getoutsourcingApi, getproductsApi} from '@/api/tickets/index'
import {handle} from '@/hook/importExecl'
import {apiDataStore} from '@/store/modules/apiData'
import throttle from 'lodash/throttle'
import {useRoute} from 'vue-router'
const route = useRoute()
const apiStore = apiDataStore()
const {proxy} = getCurrentInstance();

let sumWidth = ref(0)
let sumHeight = ref(0)
let sumQuantityPerPiece = ref(0)
let sumNumber = ref(0)
let sumSalePrice = ref(0)
let sumAmount = ref(0)


// 显示搜索到的值
let {SearchHandler} = inputSearchHandler()
const multipleTableRef = ref(null)

let $emit = defineEmits(['createTable', 'deleteRow', 'excelTable'])
// 增加每行的id属性
let i = ref(0)
let props = defineProps({
  boder: {
    type: Boolean,
    default: false,
  },
  bg: {
    type: String,
    default: '#9419FF',
    required: false // 是否必传
  },
  dataTable: {
    type: Array,
    default: [],
    required: true // 是否必传
  },
  updateFlag: {
    type: Boolean,
    default: true,
  },
  uploadeExls: {
    type: Boolean,
    default: false,
  },
  disabledFlagOuter: {
    type: Boolean,
    default: false,
  }
})
// 业务类型 
let selectBusiness = ref([
  {
    label: '物料类',
    index: 0
  },
  {
    label: '门头',
    index: 1
  },
  {
    label: '装修类',
    index: 2
  },
  {
    label: '活动类',
    index: 3
  },
  {
    label: '其他',
    index: 4
  },
])

// 成本类型
let selectCost = ref([
  {
    label: '月结供应商',
    index: 0
  },
  {
    label: '月结工时费',
    index: 1
  },
  {
    label: '现结供应商',
    index: 2
  },
  {
    label: '现结工时费',
    index: 3
  },
  {
    label: '城管费',
    index: 4
  }
])


watch(() => props.dataTable, val => {
  let data1 = 0
  let data2 = 0
  val.forEach(v => {
    data1 += Number(v.quantityPerPiece)
    data2 += Number(v.salePrice)
  })
  sumQuantityPerPiece.value = data1
  sumSalePrice.value = data2
}, {
  deep: true
})
// 存货名称
const stocksChange = (v) => {
  let arr = [v]
  arr.forEach(item => {
    apiStore.stocksData.forEach(data => {
      if (data.productId == item.productId) {
        item.price = data.price
        item.unit = data.unit
        item.productName = data.productName
      }
    })
  })
}
// 外协上
const outsourcingChange = (v) => {
  let arr = [v]

  arr.forEach(item => {
    apiStore.selectExternalDate.forEach(data => {
      if (data.outsourcingId == item.outsourcingId) {
        item.outsourcingName = data.outsourcingName
      }
    })
  })
}
// 复制
const copyRow = (row) => {
  let copyData = JSON.parse(JSON.stringify(row))
  copyData.deleteFlag = true
  if (copyData.id) {
    copyData.id = null
  }
  if (props.disabledFlagOuter == false) {
    $emit('createTable', copyData)
  }
}
// 创建一行节流
const createtable = throttle(function () {
  let data = {
    businessType: null,   //业务类型
    productId: null,    // 存货名称
    productionContent: null,       // 制作内容
    width: null,     // 宽
    height: null,     // 高
    quantityPerPiece: 1,     // 件数
    totalQuantity: 1,          // 数量
    unit: 0,           //单位
    salePrice: 0,         // 销售单价
    amount: 0,         // 销售金额
    price: 0,
    salePriceAll: 0,          // 成本金额
    prepayment: 0,        // 预收款
    materialFee: 0,  //  材料费
    outsourcingId: [],          //外协商
    costCategory: null,       // 成本类型
    budgetCost: 0,         // 预算成本
    actualCost: 0,         // 实际成本
    deleteFlag: true,         // 实际成本
  }
  if (props.disabledFlagOuter == false) {
    $emit('createTable', data)
  }
}, 500)

// 删除一行
const deleteRow = (v) => {
  if (props.disabledFlagOuter == false){
    $emit('deleteRow', v)
  }
}

// 封装请求下拉菜单信息
const getDropDownData = (res) => {
  let {code, data} = res
  if (code == 200) {
    return data
  }
}
// 获取存货下拉菜单数据
const getproductsApiData = async (data = '') => {
  if (apiStore.stocksData.length > 0) return
  let params = {deptName: data}
  let res = await getproductsApi(params)
  apiStore.stocksData = getDropDownData(res)
}
// 获取外协下拉菜单数据
const getoutsourcingApiData = async (data = '') => {
  if (apiStore.selectExternalDate.length > 0) return
  let params = {deptName: data}
  let res = await getoutsourcingApi(params)
  apiStore.selectExternalDate = getDropDownData(res)
}

let tableData = ref([])

// 暂存表格数据
let dataExacl = ref([])
const uploadHandle = async (ev) => {
  tableData.value = []
  dataExacl.value = []
  await handle(tableData.value, ev)
  tableData.value.forEach((v, i) => {
    const productItem = apiStore.stocksData.find(item => item.productName == v.in1);
    const outsourcingItem = apiStore.selectExternalDate.find(item => item.outsourcingName == v.in14);
    // if(!productItem)  proxy.$modal.msgError( `该制作内容没有建档!`);
    // if(!outsourcingItem)  proxy.$modal.msgError( `该外协商没有建档!!`);


    dataExacl.value.push({
      businessType: v.in0,   //业务类型
      productId: productItem?.productId ? productItem?.productId : null,  // 存货名称
      productionContent: v.in2 ? v.in2 : null,       // 制作内容
      width: v.in3 ? v.in3 : null,     // 宽
      height: v.in4 ? v.in4 : null,     // 高
      quantityPerPiece: v.in5 ? v.in5 : 1,     // 件数
      totalQuantity: v.in6 ? v.in6 : 1,          // 数量
      unit: productItem?.unit ? productItem?.unit : null,           //单位
      salePrice: v.in8 ? v.in8 : 0,         // 销售单价
      amount: v.in9 ? v.in9 : 0,         // 销售单价
      price: v.in10 ? v.in10 : 0,
      salePriceAll: v.in11 ? v.in11 : 0,          // 成本金额
      prepayment: v.in12 ? v.in12 : 0,        // 预收款
      materialFee: v.in13 ? v.in13 : 0,  //  材料费
      // installationFee2: v.in14 ? v.in14 : 0,    // 安装费(按天)
      // installationFee: v.in15 ? v.in15 : 0,    // 安装费
      // urbanManagementFee: v.in16 ? v.in16 : 0,  // 城管费
      outsourcingId: outsourcingItem?.outsourcingId ? outsourcingItem?.outsourcingId : null,          //外协商
      costCategory: v.in15 ? v.in15 : null,       // 成本类型
      budgetCost: v.in16 ? v.in16 : 0,         // 预算成本
      actualCost: v.in17 ? v.in17 : 0,         // 实际成本
    })
  })

  console.log(dataExacl.value);
  $emit('excelTable', dataExacl.value)
}


const cellClassName = ({row, column, rowIndex, columnIndex}) => {
  row.index = rowIndex;
  column.index = columnIndex
}

let focusCell = ref('')
let colIndex = ref(0)
let rowIndex = ref(0)
// 聚焦单元格
const updateFocusCell = (row, col) => {
  colIndex.value = col.index
  rowIndex.value = row.index
  focusCell.value = 'cellId' + ',' + String(colIndex.value) + ',' + String(rowIndex.value)
}

let tableRef = ref(null)

onMounted(() => {
  getproductsApiData()
  getoutsourcingApiData()
  tableRef.value = document.querySelector('.table-new')
  tableRef.value.addEventListener('keyup', function (event) {
    switch (event.key) {
      case 'ArrowUp':
        if (rowIndex.value > 0) {
          focusCell.value = 'cellId' + ',' + String(colIndex.value) + ',' + String(--rowIndex.value)
        }
        break;
      case 'ArrowDown':
        if (rowIndex.value < props.dataTable.length - 1) {
          focusCell.value = 'cellId' + ',' + String(colIndex.value) + ',' + String(++rowIndex.value)
        }
        break;
      case 'ArrowLeft':
        if (colIndex.value > 1) {
          focusCell.value = 'cellId' + ',' + String(--colIndex.value) + ',' + String(rowIndex.value)
        }
        break;
      case 'ArrowRight':
        if (colIndex.value < Object.keys(props.dataTable[0]).length - 2) {
          focusCell.value = 'cellId' + ',' + String(++colIndex.value) + ',' + String(rowIndex.value)
        }
        break;
      default:
        break;

    }
  });
})
const multipleSelection = ref([])

// 拿到勾选的对象
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleNumberInput = (e) => {
  //如果是上下左右，则preventDefault
  if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
    e.preventDefault()
  }
}

let deleteFlag = ref(false)
onMounted(()=>{
  if(route.path == '/tickets/todo'){
    deleteFlag.value = true
  }
})

</script>
<style lang='scss'>
.common {
  .el-scrollbar__bar {
    height: 9px;
  }

  .table-new {
    width: 100%;

    .el-table .el-table__header-wrapper th {
      height: 34px !important;
    }

    .el-table__inner-wrapper {
      height: 100% !important;
    }

    .el-table__cell {
      border-bottom: 1px solid #041661;
      border-left: 1px solid #041661;
      border-right: 1px solid #041661;
      padding: 0;
      height: 48px;

      .cell {
        height: 100%;
        padding: 0;

        .el-select {
          width: 100%;
          height: 100%;

          .select-trigger {
            width: 100%;
            height: 100%;

            .el-input {
              width: 100%;
              height: 100%;
              border: none;
            }
          }
        }

        input {
          border: none;
          outline: none;
        }

        textarea {
          cursor: pointer;
          outline: none;
        }

        :deep(.el-textarea:hover) {
          border: 1px solid red;

        }

        .el-textarea {
          border: none;
          outline: none;
          width: 100%;
          height: 100%;
          text-align: center;

          .el-textarea__inner {
            display: flex;
            align-items: center;
            width: 100%;
            height: 100%;
            text-align: center;
            outline: none;
            line-height: 100%;
          }
        }
      }
    }

    .el-popper {
      width: 120px;
      min-width: 110px !important;
      padding: 0 !important;
      font-family: PingFang SC, PingFang SC;

      .table-setting {
        text-align: center;

        p {
          margin: 0;
          height: 40px;
          line-height: 40px;
        }

        & :hover {
          background-color: #7386d1b2;
          color: #fff;
        }
      }
    }

    .cell {
      display: flex;
      align-items: center;
      justify-content: center;

      .active {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 23px;
        height: 23px;
        background: linear-gradient(180deg, #E2E7FF 0%, #FFFFFF 100%);
        border-radius: 4px 4px 4px 4px;
      }
    }
  }

  .count {
    label {
      font-size: 14px;
      font-weight: 550;
      color: #666;
      margin: 20px 30px;

      span {
        font-weight: 700;
        color: #333;
      }
    }
  }
}
.classErrorBorder{
  background-color: red;
}
</style>
